/* !
 * @Author: miss-tree
 * @Date: 2025-10-02 22:28:27
 * @Description: 全局异常过滤器
*/
import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import * as requestIp from 'request-ip';


@Catch()
export class AllExceptionsFilter implements ExceptionFilter { 
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
  catch(exception: any, host: ArgumentsHost) {
    const { httpAdapter } = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest();
    const status = exception.getStatus ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    httpAdapter.reply(response, {
      message: exception.message || '服务器错误',
      error: exception.name || 'Internal Server Error',
      code: exception.code || '500',
      body: request.body,
      query: request.query,
      ip: requestIp.getClientIp(request),
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    }, status);
  }
}